﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

using System.Net.Sockets;
using System.Net;
using TekaMUD.Engine.Framework;
using TekaMUD.Engine.IO;
using TekaMUD.Engine.Blocks;
using TekaMUD.Engine;

namespace TekaMUD.Engine.Workers
{
	public class WorkerThreadNetworkServer : WorkerThread, ISingleWorker
	{
		private int tcpPort;

		public WorkerThreadNetworkServer(int port) : base("Network server Thread")
		{
			tcpPort = port;
		}

		protected override void Run()
		{
			while (!Terminated)
			{
				// Sleeps for a while.
				Thread.Sleep(Period);

				if(Terminated)
					goto cleanup;

				
				Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

				socket.Bind(new IPEndPoint(IPAddress.Any, tcpPort));
				socket.Listen(5);

				Logger.LogInfo("TCP server listening on port: " + tcpPort);

				while (true)
				{
					try
					{
						Socket newConnection = socket.Accept();

						Logger.LogInfo("New connection from " + (newConnection.RemoteEndPoint as IPEndPoint).Address.ToString());

						TcpNetworkChannel chan = new TcpNetworkChannel(newConnection, PlayerManager.GetNewPlayer());
						ChannelManager.RegisterNewChannel(chan);

					}
					catch (Exception ex)
					{
						Logger.LogError("Error accepting new connection :  " + ex.Message);
					}
				}
			}

		cleanup:
			Logger.LogInfo("[Thread] Network server terminated.");
		}
	}
}
